import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

typedef IndexCallback = void Function(String model);

class CarPurseListPage extends StatefulWidget {
  final int typeStr; //提现明细 2 收入明细 1
  final IndexCallback chooseV;
  CarPurseListPage(
    this.typeStr, {
    Key key,
    this.chooseV,
  }) : super(key: key);

  @override
  _CarPurseListPageState createState() => _CarPurseListPageState();
}

class _CarPurseListPageState extends State<CarPurseListPage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  int page = 1;
  List<CellModel> cellArr = [];

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    page = 1;
    cellArr?.clear();
    upCellData();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    // items.add((items.length + 1).toString());
    page = page + 1;
    upCellData();
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    _onRefresh();
  }

  void upCellData() {
    DioUtils.postHttp(
      context,
      "Usercommon/my_wallet",
      parameters: {
        "token": getData("token"),
        "page": page.toString(),
        "type": widget.typeStr.toString()
      },
      onSuccess: (t) {
        print(t);
        ListModel model = ListModel.fromJson(t);
        if (model.code == 1) {
          if (mounted) {
            widget.chooseV(model.data.balance.toString());
            setState(() {
              List<CellModel> arr = model.data.list;
              for (var i = 0; i < arr.length; i++) {
                cellArr.add(arr[i]);
              }
            });
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  Text textLabel01(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Colors.black,
        fontSize: setFontSize(30),
        fontWeight: FontWeight.bold,
      ),
    );
  }

  Text textLabel02(String str) {
    return Text(
      str,
      style: TextStyle(
        color: Color(0xFF999999),
        fontSize: setFontSize(26),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("上拉加载");
            } else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            } else if (mode == LoadStatus.failed) {
              body = Text("加载失败！点击重试！");
            } else if (mode == LoadStatus.canLoading) {
              body = Text("松手,加载更多!");
            } else {
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: cellArr == null || cellArr.length == 0
            ? Container()
            : ListView.builder(
                itemCount: cellArr.length,
                itemBuilder: _listItemBuilder,
              ),
      ),
    );
  }

  Widget _listItemBuilder(BuildContext context, int index) {
    return InkWell(
      child: Column(children: [
        Container(
          padding: EdgeInsets.fromLTRB(20, 10, 20, 0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  textLabel01(cellArr[index].memo),
                  Text(
                    widget.typeStr == 1
                        ? "+" + cellArr[index].money
                        : "-" + cellArr[index].money,
                    style: TextStyle(
                      color: widget.typeStr == 1
                          ? Color(0xFFFF2A2A)
                          : Colors.grey[700],
                      fontSize: setFontSize(34),
                      fontWeight: FontWeight.bold,
                    ),
                  )
                ],
              ),
              SizedBox(height: setHeight(16)),
              textLabel02(cellArr[index].createtimeText),
              SizedBox(height: setHeight(32)),
            ],
          ),
        ),
        Container(
          color: Colors.grey[300],
          height: 1,
        ),
      ]),
      onTap: () {},
    );
  }
}

class ListModel {
  int code;
  String msg;
  String time;
  Data data;

  ListModel({this.code, this.msg, this.time, this.data});

  ListModel.fromJson(Map<String, dynamic> json) {
    code = json['code'];
    msg = json['msg'];
    time = json['time'];
    data = json['data'] != null ? new Data.fromJson(json['data']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['code'] = this.code;
    data['msg'] = this.msg;
    data['time'] = this.time;
    if (this.data != null) {
      data['data'] = this.data.toJson();
    }
    return data;
  }
}

class Data {
  String balance;
  List<CellModel> list;

  Data({this.balance, this.list});

  Data.fromJson(Map<String, dynamic> json) {
    balance = json['balance'];
    if (json['list'] != null) {
      list = new List<CellModel>();
      json['list'].forEach((v) {
        list.add(new CellModel.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['balance'] = this.balance;
    if (this.list != null) {
      data['list'] = this.list.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CellModel {
  int id;
  String money;
  String memo;
  int type;
  int createtime;
  String createtimeText;

  CellModel(
      {this.id,
      this.money,
      this.memo,
      this.type,
      this.createtime,
      this.createtimeText});

  CellModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    money = json['money'];
    memo = json['memo'];
    type = json['type'];
    createtime = json['createtime'];
    createtimeText = json['createtime_text'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['money'] = this.money;
    data['memo'] = this.memo;
    data['type'] = this.type;
    data['createtime'] = this.createtime;
    data['createtime_text'] = this.createtimeText;
    return data;
  }
}
